package com.qinyi.framework.shiro.web.filter.Captcha;

import com.google.code.kaptcha.Constants;
import com.qinyi.common.constant.ShiroConstants;
import com.qinyi.framework.shiro.util.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author wangan on 2019/6/3
 * @description
 */
public class CaptchaValidateFilter extends AccessControlFilter {


	/**
	 * 是否开启验证码
	 */
	private boolean captchaEnabled = true;
	/**
	 * 验证码类型
	 */
	private String captchaType = "math";

	public boolean isCaptchaEnabled() {
		return captchaEnabled;
	}

	public void setCaptchaEnabled(boolean captchaEnabled) {
		this.captchaEnabled = captchaEnabled;
	}

	public String getCaptchaType() {
		return captchaType;
	}

	public void setCaptchaType(String captchaType) {
		this.captchaType = captchaType;
	}

	@Override
	public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		request.setAttribute(ShiroConstants.CURRENT_ENABLED, captchaEnabled);
		request.setAttribute(ShiroConstants.CURRENT_TYPE, captchaType);
		return super.onPreHandle(request, response, mappedValue);
	}

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		if (!captchaEnabled || !"post".equals(servletRequest.getMethod().toLowerCase())) {
			return true;
		}
		String validateCode = request.getParameter(ShiroConstants.CURRENT_VALIDATECODE);
		String code = String.valueOf(ShiroUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
		if (StringUtils.isEmpty(validateCode) || !StringUtils.equals(code, validateCode)) {
			return false;
		}
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		return false;
	}
}
